import { Avatar, Divider, Drawer, Input, Message, Switch, Trigger } from "@arco-design/web-react";
import { IconClose, IconDelete, IconDown, IconEdit, IconMinus, IconPlus, IconRight, IconSearch, IconSubscribe, IconUp } from "@arco-design/web-react/icon";
import { UserInfo } from "os";
import React, { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { LeoAvatar } from "../../../components/leo_Avatar";
import { Popup } from "@arco-design/mobile-react";
import { UserModelElement } from "../../friend/components/user_model";
import { AddFriendModel } from "../../friend/components/add_friend";
import { ChatContext } from "..";
import FormItem from "@arco-design/web-react/es/Form/form-item";
import http from "../../../http";
import { fetchConversationList } from "../../../store/features/conversation";
import { forceRefreshFriendList, refreshFriendList } from "../../../store/features/friend";




const GroupMemberUserInfo: React.FC<any> = ({ userInfo, topRef }) => {

    const [popupVisible, setPopupVisible] = useState(false);

    const [visibleAdd, setVisibleAdd] = useState(false);

    const users = useSelector((state: any) => state.friend.value.users);

    const clickAddFriend = () => {
        setPopupVisible(false);
        setVisibleAdd(true);
    }



    if (users && userInfo) {
        let firendUser = users.find((item: any) => item.userId == userInfo.userId);
        if (firendUser) {
            if (firendUser.remark) {
                userInfo = { ...userInfo, remark: firendUser.remark }
            }
        }
    }

    const popup = (
        <div>
            <div className="bg-white py-5 px-5 rounded-xl  shadow-2xl">
                <UserModelElement clickAddFriend={clickAddFriend} userInfo={userInfo} />
            </div>;
        </div>
    )




    return <div >
        <AddFriendModel userInfo={userInfo} visibleAdd={visibleAdd} setVisibleAdd={setVisibleAdd} ></AddFriendModel>
        <Trigger
            popupVisible={popupVisible}
            onVisibleChange={(visible) => setPopupVisible(visible)}
            getPopupContainer={(): any => topRef && topRef.current}
            popup={() => popup}
            trigger={['click']}
            position="lt"
            clickToClose={false}>
            <div className="flex flex-col mt-1 w-[70px] justify-center items-center">
                <LeoAvatar userPortrait={userInfo.userPortrait} userName={userInfo.nickName}></LeoAvatar>
                <div className="mt-[3px] text-[12px] break-words text-ellipsis w-[70px] text-center line-clamp-1">
                    {userInfo.remark ? userInfo.remark : userInfo.nickName}
                </div>
            </div>
        </Trigger>
    </div>;
}


export const DrawerGroupInfo: React.FC<any> = ({ visibleGroup, refWrapper, topRef, setVisibleGroupInfo, targetId, conversation }) => {

    const [groupText, setGroupText] = useState<string>("");
    const dispatch = useDispatch();


    const groupMap = useSelector((state: any) => state.group.value);

    const groupMember = useSelector((state: any) => state.groupMember.value);



    const { groupNoticeVisible, openGroupNoticeModel } = useContext(ChatContext);


    return <Drawer
        style={{ width: '40%', }}
        title={null}
        closeIcon={null}
        visible={visibleGroup}
        getPopupContainer={(): any => refWrapper && refWrapper.current}
        footer={null}
        onOk={() => {
            setVisibleGroupInfo(false);
        }}
        onCancel={() => {
            setVisibleGroupInfo(false);
        }}
    >
        <div className="flex flex-col w-full h-full p-[16px]">

            <div className="px-[6px]">
                <Input
                    onChange={(v) => setGroupText(v)}
                    className=" mb-2"
                    style={{ height: 40 }}
                    maxLength={11}
                    prefix={<IconSearch />}

                    placeholder='搜索群成员'
                />
            </div>
            {
                groupText ?
                    <div className="grid grid-cols-5 justify-items-center cursor-pointer">
                        {
                            groupMember[targetId]?.filter((item: any) =>
                                item.nickName.includes(groupText)).map((item: any) => <GroupMemberUserInfo key={`${item.fp}j`} topRef={topRef} userInfo={item} />)
                        }
                    </div> :

                    <div className="flex-grow">
                        <GroupMembers group={groupMap[targetId]} topRef={topRef} users={groupMember[targetId]}></GroupMembers>



                        <div className="flex flex-col justify-start items-start mt-3">
                            <div className="text-black font-normal  text-[13px]">群聊名称</div>
                            <Input normalize={(value) => {

                                if(groupMap[targetId]?.groupName != value){
                                    const fetchUser = async () => {
                                        const response: any = await http.get(`/group/updateName?targetId=${targetId}&name=${value}`)
                                        if (response.code == 200) {
                                            Message.success("修改成功");
                                        } else {
                                            Message.error(response.msg);
                                        }
                                    }
                                    fetchUser();
                                }
                               
                                return value;
                            }} className='bg-transparent h-[24px] text-[12px] text-gray-500 pl-0' defaultValue={groupMap[targetId]?.groupName} placeholder='' />
                        </div>

                        <div className="flex flex-col justify-start items-start mt-3">
                            <div className="text-black font-normal  text-[13px]">备注</div>
                            <Input
                                defaultValue={conversation.remark}
                                normalize={(value) => {

                                    if(value != conversation.remark){
                                        const fetchUser = async () => {
                                            const response: any = await http.get(`/conversation/setRemark?groupId=${targetId}&name=${value}`)
                                            if (response.code == 200) {
                                                Message.success("修改成功");
                                                dispatch(fetchConversationList(targetId))
                                                dispatch(refreshFriendList())
                                            } else {
                                                Message.error(response.msg);
                                            }
                                        }
                                        fetchUser();
                                    }
                                    


                                    return value;
                                }}

                                className='bg-transparent h-[24px] text-[12px] text-gray-500 pl-0' placeholder='群聊备注仅自己可见' />
                        </div>




                        <div className="flex flex-row  leading-[50px]  cursor-pointer" onClick={() => {
                            openGroupNoticeModel(groupMap[targetId]);
                        }}>
                            <div className="w-[86px] flex-shrink-0 text-left">群公告</div>
                            <div className="w-full whitespace-break-spaces text-right">
                                <IconRight></IconRight>
                            </div>
                        </div>

                        <Divider className='m-0 p-0'></Divider>

                        <div className="flex flex-row leading-[40px]   cursor-pointer">
                            <div className="w-[86px] flex-shrink-0 text-left">免打扰</div>
                            <div className="w-full text-right whitespace-break-spaces">
                                <Switch checked={conversation.disturb} onChange={()=> {
                                     const fetchData = async () => {
                                        const respone = await http.get(`/conversation/setDisturb?targetId=${conversation.targetId}`)
                                        dispatch(fetchConversationList(conversation.targetId))
                                    }
                                    fetchData();
                                }} />
                            </div>
                        </div>

                        <div className="flex flex-row  leading-[40px]  cursor-pointer">
                            <div className="w-[86px] flex-shrink-0 text-left">置顶聊天</div>
                            <div className="w-full text-right whitespace-break-spaces">
                                <Switch checked={conversation.top} onChange={()=> {
                                     const fetchData = async () => {
                                        const respone = await http.get(`/conversation/top?targetId=${conversation.targetId}`)
                                        dispatch(fetchConversationList(conversation.targetId))
                                    }
                                    fetchData();
                                }} />
                            </div>
                        </div>

                        <div className="flex flex-row leading-[40px] cursor-pointer">
                            <div className="w-[86px] flex-shrink-0 text-left">保存到通讯录</div>
                            <div className="w-full text-right whitespace-break-spaces">
                                <Switch  />
                            </div>
                        </div>


                        <Divider className='m-0 p-0'></Divider>
                        <div className="w-full text-center leading-[50px] text-red-400 font-bold ">清空聊天记录</div>

                        <Divider className='m-0 p-0'></Divider>

                        <div className="w-full text-center leading-[50px] text-red-400 font-bold ">退出群聊</div>
                    </div>
            }
        </div>
    </Drawer >
}


export const GroupMembers: React.FC<any> = ({ users, topRef, group }) => {


    const { invitationGroupUser, removeGroupUser } = useContext(ChatContext);

    const [list, setList] = useState<any>([]);

    const [open, setOpen] = useState<boolean>(false);

    const user = useSelector((state: any) => state.user.value.user);


    useEffect(() => {
        if (users) {
            setList(users.slice(0, 19));
        }

    }, [users])

    useEffect(() => {
        if (users) {
            const lists = open ? users : users.slice(0, 19);
            setList(lists);
        }
    }, [open])




    return <>
        <div className="grid grid-cols-4 justify-items-center cursor-pointer mt-2 mb-3">
            {
                list && list.map((item: any) => <GroupMemberUserInfo key={`${item.userId}kkkk`} topRef={topRef} userInfo={item} />)
            }
            <div onClick={() => {
                invitationGroupUser();
            }} className="flex flex-col mt-1 w-[70px] justify-center items-center">
                <div className="w-[40px] h-[40px] bg-gray-200 rounded-lg text-center leading-[40px] text-[16px]">
                    <IconPlus></IconPlus>
                </div>
                <div className="mt-[3px] text-[12px]">添加</div>
            </div>
            {
                group && group.creator == user.userId &&
                <div onClick={() => {
                    removeGroupUser(list);
                }} className="flex flex-col mt-1 w-[70px] justify-center items-center">
                    <div className="w-[40px] h-[40px] bg-gray-200 rounded-lg text-center leading-[40px] text-[16px]">
                        <IconMinus />
                    </div>
                    <div className="mt-[3px] text-[12px]">移除</div>
                </div>
            }
        </div>
        {
            users && users.length >= 20 && <div className="mt-2 cursor-pointer text-[12px] font-bold text-gray-400" onClick={() => setOpen(!open)}>
                {
                    !open ? <> 展开更多 <IconDown></IconDown></> : <> 收起 <IconUp></IconUp></>
                }
            </div>
        }

        <Divider className='m-0 p-0 mt-[10px]'></Divider>
    </>;
}